<template>
  <div class="kikimami-dashboard-container">
    <!-- 竖向触发按钮 -->
    <div 
      class="trigger-button"
      @mouseenter="handleTriggerHover"
      :class="{ 'hidden': visible && !autoHide }"
    >
      <div class="vertical-text">看板</div>
      <div class="arrow-icon">
        <i class="left-arrow">◀</i>
      </div>
    </div>
    
    <!-- 主面板 -->
    <div 
      v-if="visible" 
      id="kikimami-dashboard-panel" 
      :style="panelStyle"
      ref="dashboardPanel"
      @mouseleave="handlePanelLeave"
    >
      <!-- 面板头部 -->
      <div 
        :style="headerStyle" 
        ref="panelHeader"
        @mousedown="startDrag"
      >
        <h2 :style="titleStyle">客户状态看板</h2>
        <div class="header-actions">
          <button 
            :style="pinButtonStyle" 
            @click="toggleAutoHide"
            :class="{ 'active': !autoHide }"
            title="固定面板"
          >
            <span class="pin-icon">📌</span>
          </button>
          <button 
            :style="closeButtonStyle" 
            @click="hide"
            @mouseover="closeButtonHover = true"
            @mouseout="closeButtonHover = false"
            title="关闭"
          >&times;</button>
        </div>
      </div>
      
      <!-- 面板内容容器 -->
      <div :style="contentContainerStyle">
        <!-- 加载状态显示 -->
        <div v-if="loading" :style="loadingStyle">加载中...</div>
        <div v-else-if="error" :style="errorStyle">{{ error }}</div>
        
        <div v-else-if="dashboardData">
          <!-- 选项卡导航 -->
          <div :style="tabsNavStyle">
            <button 
              v-for="tab in availableTabs" 
              :key="tab.key"
              :style="getTabStyle(tab.key === activeTab)"
              @click="handleTabClick(tab.key)"
            >
              {{ tab.label }} ({{ getTabCount(tab.key) }})
            </button>
          </div>
          
          <!-- 选项卡内容 -->
          <div :style="tabContentStyle">
            <div v-if="getCurrentTabData().length === 0" :style="emptyStateStyle">
              暂无数据
            </div>
            <div v-else>
              <!-- 客户列表 -->
              <div 
                v-for="customer in getCurrentTabData()" 
                :key="customer.id"
                :style="customerItemStyle(customer.id || customer._serialized)"
                @click="handleCustomerClick(customer)"
              >
                <div :style="customerAvatarContainerStyle">
                  <img 
                    v-if="customer.avatar" 
                    :src="customer.avatar" 
                    :style="avatarStyle"
                    alt="头像"
                  />
                  <div v-else :style="defaultAvatarStyle">
                    {{ getInitials(customer.nickname || customer.name) }}
                  </div>
                </div>
                
                <div :style="customerInfoStyle">
                  <div :style="customerNameStyle">
                    {{ customer.nickname || customer.name }}
                  </div>
                  <div :style="customerIdStyle">
                    {{ customer._serialized }}
                  </div>
                  <div :style="lastMessageTimeStyle">
                    {{ customer.lastmessage_at_short }}
                  </div>
                </div>
                
                <div :style="customerStatusStyle">
                  <div v-if="customer.need_replay" :style="needReplyBadgeStyle">
                    需回复
                  </div>
                  <div v-if="customer.crmorder" :style="orderBadgeStyle">
                    订单: {{ customer.crmorder.order_no }}
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onBeforeUnmount, CSSProperties, watch, inject, onMounted, nextTick } from 'vue';
import { getDashboardData } from '../utils/erpapi';
import { searchAndOpenChat } from '../utils/domtools';
import { handleChatDataUpdate } from '../utils/chatDataHandler';
// 检查是否处于内嵌模式
const inlineMode = inject('$inlineMode', false);
console.log('KikimamiDashboardPanel 组件初始化，内嵌模式:', inlineMode);

// 定义容器位置信息类型
type ContainerRect = {
  top: number;
  left: number;
  width: number;
  height: number;
};

// 获取容器位置信息
const containerRect = inject<ContainerRect | null>('containerRect', null);
console.log('容器位置信息:', containerRect);

// 状态
const visible = ref(false);
const rightPosition = ref(0);
const isDragging = ref(false);
const startX = ref(0);
const startRight = ref(0);
const closeButtonHover = ref(false);
// 添加自动隐藏状态
const autoHide = ref(true);

// 看板数据相关状态
const dashboardData = ref<any>(null);
const loading = ref(false);
const error = ref<string | null>(null);
// 添加标志变量，跟踪当前显示周期内是否已获取数据
const dataFetchedInCurrentSession = ref(false);
// 添加变量跟踪当前被点击的客户ID
const selectedCustomerId = ref<string | null>(null);

// 组件挂载后的处理
onMounted(() => {
  console.log('KikimamiDashboardPanel 组件已挂载，内嵌模式:', inlineMode);
  console.log('面板可见状态:', visible.value);
  console.log('面板元素:', document.getElementById('kikimami-dashboard-panel'));
});

// 选项卡状态
const activeTab = ref('focus_follow');

// 可用的选项卡
const availableTabs = [
  { key: 'focus_follow', label: '重点跟进中' },
  { key: 'high_potential', label: '重点潜客' },
  { key: 'potential', label: '一般潜客' }
];

// 获取选项卡数据数量
const getTabCount = (tabKey: string) => {
  if (!dashboardData.value || !dashboardData.value[tabKey]) {
    return 0;
  }
  return dashboardData.value[tabKey].count || 0;
};

// 获取当前选项卡数据
const getCurrentTabData = () => {
  if (!dashboardData.value || !dashboardData.value[activeTab.value]) {
    return [];
  }
  return dashboardData.value[activeTab.value].data || [];
};

// 当用户点击选项卡时处理状态更新
const handleTabClick = async (tabKey: string) => {
  activeTab.value = tabKey;
  // 重置选中状态
  selectedCustomerId.value = null;
  // 调用状态看板点击处理函数，传入当前选中的状态
  await handleStatusBoardClick(tabKey);
};

// 获取名称首字母作为默认头像
const getInitials = (name: string) => {
  if (!name) return '?';
  return name.charAt(0).toUpperCase();
};

// 处理客户点击事件
const handleCustomerClick = async (customer: any) => {
  try {
    console.log('客户点击事件触发，客户数据:', customer);
    
    // 设置当前选中的客户ID
    selectedCustomerId.value = customer.id || customer._serialized;
    
    // 获取客户名称或昵称
    const customerName = customer.name || customer.nickname || customer._serialized;
    if (!customerName) {
      console.warn(' handleCustomerClick 客户名称为空，无法在WhatsApp中搜索');
      return;
    }
    
    console.log(`handleCustomerClick 准备在WhatsApp中搜索客户: ${customerName}`);
    
    // 在WhatsApp搜索框中输入客户名称
    try {
      const success = await searchAndOpenChat(customerName);
      if (success) {
        console.log(`handleCustomerClick 已在WhatsApp中搜索客户并打开对话: ${customerName}`);
        // 此处调用 handleChatDataUpdate
        await handleChatDataUpdate(customer._serialized, true);
        // 如果在内嵌模式下，可能需要隐藏面板
        if (inlineMode) {
          console.log('handleCustomerClick 内嵌模式下，打开对话后隐藏面板');
          hide();
        }
      } else {
        console.error(`在WhatsApp中搜索客户失败: ${customerName}`);
      }
    } catch (searchError) {
      console.error('搜索客户时发生错误:', searchError);
      
      // 尝试备用方法：直接在搜索框中输入
      try {
        const searchInput = document.querySelector('#side div[data-lexical-editor="true"]') as HTMLDivElement;
        if (searchInput) {
          console.log('尝试备用方法：直接设置搜索框内容');
          searchInput.textContent = customerName;
          searchInput.dispatchEvent(new Event('input', { bubbles: true }));
        }
      } catch (fallbackError) {
        console.error('备用方法也失败了:', fallbackError);
      }
    }
  } catch (error) {
    console.error('处理客户点击事件时出错:', error);
    if (error instanceof Error) {
      alert(`搜索客户失败: ${error.message}`);
    } else {
      alert('搜索客户失败: 未知错误');
    }
  }
};

// 获取看板数据
const fetchDashboardData = async (status?: string) => {
  // 如果当前会话已经获取过数据且没有指定状态参数，则跳过
  if (dataFetchedInCurrentSession.value && !status) {
    console.log('当前会话已获取过数据，跳过重复请求');
    return;
  }

  loading.value = true;
  error.value = null;
  let retryCount = 0;
  const maxRetries = 3;
  
  const tryFetch = async () => {
    try {
      // 使用状态参数获取数据
      const data = await getDashboardData(status);
      console.log('获取到的看板数据:', data);
      
      // 检查数据结构
      if (!data) {
        console.error('获取到的数据为空');
        error.value = '获取数据失败，返回数据为空';
        return false;
      }
      
      // 如果是首次加载或没有指定状态，直接替换整个数据
      if (!dashboardData.value || !status) {
        dashboardData.value = data;
      } else {
        // 如果指定了状态，只更新该状态的数据，保留其他状态的数据
        const newData = { ...dashboardData.value };
        // 检查返回的数据结构，确保正确更新
        if (data[status]) {
          // 如果返回的数据包含指定状态的数据
          newData[status] = data[status];
        } else {
          // 如果返回的数据结构不符合预期，尝试智能处理
          // 假设返回的是单个状态的数据
          newData[status] = data;
        }
        dashboardData.value = newData;
      }
      
      console.log('更新后的看板数据:', dashboardData.value);
      
      // 标记为已获取数据
      dataFetchedInCurrentSession.value = true;
      return true; // 成功获取数据
    } catch (err: any) {
      console.error(`获取看板数据失败 (尝试 ${retryCount + 1}/${maxRetries}):`, err);
      
      // 检查是否是扩展上下文失效错误
      if (err.message && (
          err.message.includes('Extension context invalidated') || 
          err.message.includes('获取存储数据失败')
        )) {
        // 这类错误通常无法通过重试解决，直接显示友好错误信息
        error.value = '扩展状态异常，请刷新页面或重启浏览器后重试';
        return false;
      }
      
      // 其他错误可以尝试重试
      if (retryCount < maxRetries - 1) {
        retryCount++;
        // 指数退避重试
        const delay = Math.pow(2, retryCount) * 1000;
        console.log(`将在 ${delay}ms 后重试...`);
        await new Promise(resolve => setTimeout(resolve, delay));
        return await tryFetch(); // 递归重试
      } else {
        // 达到最大重试次数
        error.value = err.message || '获取数据失败，请稍后重试';
        return false;
      }
    }
  };
  
  try {
    await tryFetch();
  } finally {
    loading.value = false;
  }
};

// 监听显示状态变化
const togglePanel = () => {
  console.log('togglePanel调用前:', visible.value);
  const wasVisible = visible.value;
  visible.value = !visible.value;
  console.log('togglePanel调用后:', visible.value);
  
  if (visible.value) {
    // 只有在数据为空时才获取数据
    if (!dashboardData.value) {
      // 重置数据获取标志
      dataFetchedInCurrentSession.value = false;
      // 获取初始数据，使用当前活动选项卡作为状态
      fetchDashboardData(activeTab.value);
    }
  } else {
    // 从显示变为隐藏时，不重置数据获取标志，保留数据
    // 重置选中状态
    selectedCustomerId.value = null;
  }
};

// 添加watch来监控visible的变化
watch(visible, (newVal, oldVal) => {
  console.log('visible值变化:', oldVal, '->', newVal);
});

// 计算样式
const panelStyle = computed<CSSProperties>(() => {
  // 基础样式
  const baseStyle: CSSProperties = {
    backgroundColor: '#fff',
    boxShadow: '-5px 0 15px rgba(0,0,0,0.2)',
    padding: '0',
    boxSizing: 'border-box',
    display: 'flex',
    flexDirection: 'column',
    width: '400px',
    height: '100vh',
    position: 'fixed',
    top: 0,
    right: 0,
    zIndex: 9999,
    overflow: 'hidden',
    transition: 'all 0.3s ease'
  };
  
  // 根据模式应用不同样式
  if (inlineMode) {
    // 内嵌模式样式
    if (containerRect) {
      return {
        ...baseStyle,
        height: `${containerRect.height}px`,
        backgroundColor: '#fff',
        boxShadow: '-5px 0 15px rgba(0,0,0,0.5)',
        border: '1px solid #ddd'
      };
    }
  }
  
  // 浮动模式样式
  return baseStyle;
});

const headerStyle = computed<CSSProperties>(() => ({
  backgroundColor: '#ff6b6b',
  color: 'white',
  padding: '15px 20px',
  display: 'flex',
  justifyContent: 'space-between',
  alignItems: 'center',
  borderBottom: '1px solid #e0e0e0',
  borderRadius: '8px 0 0 0',
  cursor: 'move'
}));

const titleStyle = computed<CSSProperties>(() => ({
  margin: '0',
  padding: '0',
  fontSize: '18px',
  fontWeight: 'bold'
}));

const closeButtonStyle = computed<CSSProperties>(() => ({
  background: closeButtonHover.value ? 'rgba(255, 255, 255, 0.2)' : 'transparent',
  border: 'none',
  color: 'white',
  fontSize: '24px',
  cursor: 'pointer',
  padding: '0 5px',
  lineHeight: '1',
  display: 'flex',
  alignItems: 'center',
  justifyContent: 'center',
  width: '30px',
  height: '30px',
  borderRadius: '50%',
  transition: 'background-color 0.2s'
}));

const contentContainerStyle = computed<CSSProperties>(() => ({
  padding: '20px',
  overflowY: 'auto',
  flex: '1',
  height: 'calc(100vh - 60px)',
  boxSizing: 'border-box'
}));

// 选项卡样式
const tabsNavStyle = computed<CSSProperties>(() => ({
  display: 'flex',
  borderBottom: '1px solid #e0e0e0',
  marginBottom: '15px'
}));

const getTabStyle = (isActive: boolean): CSSProperties => ({
  padding: '10px 15px',
  border: 'none',
  background: 'none',
  borderBottom: isActive ? '2px solid #ff6b6b' : 'none',
  color: isActive ? '#ff6b6b' : '#666',
  fontWeight: isActive ? 'bold' : 'normal',
  cursor: 'pointer',
  flex: '1',
  transition: 'all 0.2s'
});

const tabContentStyle = computed<CSSProperties>(() => ({
  marginBottom: '20px'
}));

// 客户列表项样式
const customerItemStyle = computed(() => {
  return (customerId: string) => {
    const isSelected = selectedCustomerId.value === customerId;
    return {
      display: 'flex',
      padding: '12px',
      borderBottom: '1px solid #f0f0f0',
      alignItems: 'center',
      transition: 'background-color 0.2s',
      cursor: 'pointer',
      backgroundColor: isSelected ? '#e6f7ff' : 'transparent', // 选中时使用浅蓝色背景
      ':hover': {
        backgroundColor: isSelected ? '#e6f7ff' : '#f9f9f9'
      }
    } as CSSProperties;
  };
});

const customerAvatarContainerStyle = computed<CSSProperties>(() => ({
  marginRight: '12px'
}));

const avatarStyle = computed<CSSProperties>(() => ({
  width: '40px',
  height: '40px',
  borderRadius: '50%',
  objectFit: 'cover'
}));

const defaultAvatarStyle = computed<CSSProperties>(() => ({
  width: '40px',
  height: '40px',
  borderRadius: '50%',
  backgroundColor: '#ff6b6b',
  color: 'white',
  display: 'flex',
  alignItems: 'center',
  justifyContent: 'center',
  fontSize: '18px',
  fontWeight: 'bold'
}));

const customerInfoStyle = computed<CSSProperties>(() => ({
  flex: '1',
  overflow: 'hidden'
}));

const customerNameStyle = computed<CSSProperties>(() => ({
  fontWeight: 'bold',
  marginBottom: '3px',
  whiteSpace: 'nowrap',
  overflow: 'hidden',
  textOverflow: 'ellipsis'
}));

const customerIdStyle = computed<CSSProperties>(() => ({
  fontSize: '12px',
  color: '#888',
  marginBottom: '3px',
  whiteSpace: 'nowrap',
  overflow: 'hidden',
  textOverflow: 'ellipsis'
}));

const lastMessageTimeStyle = computed<CSSProperties>(() => ({
  fontSize: '12px',
  color: '#aaa'
}));

const customerStatusStyle = computed<CSSProperties>(() => ({
  display: 'flex',
  flexDirection: 'column',
  alignItems: 'flex-end',
  gap: '5px'
}));

const needReplyBadgeStyle = computed<CSSProperties>(() => ({
  backgroundColor: '#ff6b6b',
  color: 'white',
  padding: '3px 8px',
  borderRadius: '10px',
  fontSize: '12px'
}));

const orderBadgeStyle = computed<CSSProperties>(() => ({
  backgroundColor: '#4CAF50',
  color: 'white',
  padding: '3px 8px',
  borderRadius: '10px',
  fontSize: '12px'
}));

const emptyStateStyle = computed<CSSProperties>(() => ({
  textAlign: 'center',
  padding: '30px',
  color: '#888',
  fontSize: '14px'
}));

// 方法
const show = async () => {
  console.log('show方法调用前:', visible.value);
  visible.value = true;
  console.log('show方法调用后:', visible.value);
  
  // 等待下一个 DOM 更新周期
  await nextTick();
  console.log('DOM 更新后，面板元素:', document.getElementById('kikimami-dashboard-panel'));
  
  // 只有在数据为空时才获取数据
  if (!dashboardData.value) {
    // 重置数据获取标志
    dataFetchedInCurrentSession.value = false;
    // 获取初始数据，使用当前活动选项卡作为状态
    fetchDashboardData(activeTab.value);
  }
};

const hide = () => {
  console.log('hide方法调用前:', visible.value);
  visible.value = false;
  console.log('hide方法调用后:', visible.value);
  // 面板隐藏时不重置数据获取标志，保留数据
  // 重置选中状态
  selectedCustomerId.value = null;
};

const onDrag = (e: MouseEvent) => {
  if (!isDragging.value) return;
  
  const deltaX = startX.value - e.clientX;
  rightPosition.value = startRight.value + deltaX;
};

const stopDrag = () => {
  isDragging.value = false;
  
  // 移除全局事件监听
  document.removeEventListener('mousemove', onDrag);
  document.removeEventListener('mouseup', stopDrag);
};

const startDrag = (e: MouseEvent) => {
  // 如果点击的是关闭按钮，不启动拖动
  if ((e.target as HTMLElement).tagName === 'BUTTON') return;
  
  isDragging.value = true;
  startX.value = e.clientX;
  startRight.value = rightPosition.value;
  
  // 添加全局事件监听
  document.addEventListener('mousemove', onDrag);
  document.addEventListener('mouseup', stopDrag);
  
  // 防止选中文本
  e.preventDefault();
};

// 暴露方法给外部使用
defineExpose({
  show,
  hide,
  togglePanel
});

// 组件卸载前清理
onBeforeUnmount(() => {
  document.removeEventListener('mousemove', onDrag);
  document.removeEventListener('mouseup', stopDrag);
});

// 新增样式
const loadingStyle = computed<CSSProperties>(() => ({
  textAlign: 'center',
  padding: '20px',
  color: '#666'
}));

const errorStyle = computed<CSSProperties>(() => ({
  textAlign: 'center',
  padding: '20px',
  color: '#ff4444'
}));

// 当用户点击当前状态看板时
const handleStatusBoardClick = async (status: string) => {
  try {
    // 重置数据获取标志，确保可以获取新数据
    dataFetchedInCurrentSession.value = false;
    // 调用 fetchDashboardData 并传入状态参数
    await fetchDashboardData(status);
  } catch (error: any) {
    console.error('获取状态看板数据失败:', error);
    if (error instanceof Error) {
      alert(`获取状态看板数据失败: ${error.message}`);
    } else {
      alert('获取状态看板数据失败: 未知错误');
    }
  }
};

// 处理触发按钮悬停
const handleTriggerHover = () => {
  if (autoHide.value) {
    show();
  }
};

// 处理面板鼠标离开
const handlePanelLeave = () => {
  if (autoHide.value) {
    hide();
  }
};

// 切换自动隐藏状态
const toggleAutoHide = () => {
  autoHide.value = !autoHide.value;
};

// 添加固定按钮样式
const pinButtonStyle = computed<CSSProperties>(() => ({
  background: 'transparent',
  border: 'none',
  color: 'white',
  fontSize: '16px',
  cursor: 'pointer',
  padding: '0 5px',
  lineHeight: '1',
  display: 'flex',
  alignItems: 'center',
  justifyContent: 'center',
  width: '30px',
  height: '30px',
  borderRadius: '50%',
  marginRight: '5px',
  transition: 'background-color 0.2s'
}));
</script>

<style scoped>
.kikimami-dashboard-container {
  position: fixed;
  right: 0;
  top: 0;
  height: 100vh;
  z-index: 9999;
  display: flex;
  flex-direction: row-reverse;
  pointer-events: none;
}

.trigger-button, #kikimami-dashboard-panel {
  pointer-events: auto;
}

.trigger-button {
  position: relative;
  width: 40px;
  height: auto;
  padding: 8px 0;
  max-height: 80px;
  background-color: #ff6b6b;
  border-radius: 8px 0 0 8px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  box-shadow: -2px 0 10px rgba(0,0,0,0.2);
  transition: all 0.3s ease;
  color: white;
  z-index: 9998;
  margin-top: 100px; /* 从顶部固定距离 */
}

.trigger-button.hidden {
  opacity: 0;
  pointer-events: none;
}

.trigger-button:hover {
  width: 45px;
  background-color: #ff5252;
}

.vertical-text {
  writing-mode: vertical-lr;
  text-orientation: upright;
  font-size: 14px;
  font-weight: bold;
  letter-spacing: 1px;
  user-select: none;
  line-height: 1.2;
}

.arrow-icon {
  margin-top: 5px;
}

.left-arrow {
  font-style: normal;
  font-size: 14px;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 8px;
}

.pin-icon {
  opacity: 0.7;
  transition: opacity 0.2s;
}

button.active .pin-icon {
  opacity: 1;
  transform: rotate(-45deg);
}

/* 响应式样式 */
@media (max-width: 768px) {
  .trigger-button {
    width: 30px;
    padding: 6px 0;
    max-height: 100px;
  }
  
  .vertical-text {
    font-size: 14px;
  }
}

#kikimami-dashboard-panel {
  height: 100vh !important;
  display: flex;
  flex-direction: column;
  background-color: #fff;
  box-shadow: -5px 0 15px rgba(0,0,0,0.2);
  padding: 0;
  box-sizing: border-box;
  transition: all 0.3s ease;
  width: 400px;
  border-radius: 0;
  position: fixed;
  top: 0;
  right: 0;
  z-index: 9999;
  overflow: hidden;
}

/* 修改内容区域的滚动样式 */
#kikimami-dashboard-panel > div[style*="overflow-y: auto"] {
  flex: 1;
  overflow-y: auto !important;
  height: calc(100vh - 60px) !important;
}

/* 美化滚动条 */
#kikimami-dashboard-panel > div[style*="overflow-y: auto"]::-webkit-scrollbar {
  width: 6px;
}

#kikimami-dashboard-panel > div[style*="overflow-y: auto"]::-webkit-scrollbar-track {
  background: #f1f1f1;
}

#kikimami-dashboard-panel > div[style*="overflow-y: auto"]::-webkit-scrollbar-thumb {
  background: #888;
  border-radius: 3px;
}

#kikimami-dashboard-panel > div[style*="overflow-y: auto"]::-webkit-scrollbar-thumb:hover {
  background: #555;
}
</style> 